<?php

namespace App\Http\Controllers\Asset;

use App\Http\Controllers\Controller;
use App\Http\Requests\Asset\PosterRequest;
use App\Models\Asset\Poster;
use App\Models\Common\EntityData\Channel\Sp;
use App\Repositories\Asset\PosterRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;

class PosterController extends Controller
{
    use ModelForm;

    /** @var  PosterRepository */
    private $posterRepository;

    public function __construct(PosterRepository $posterRepo)
    {
        $this->posterRepository = $posterRepo;
    }

    /**
     * Display a listing of the Poster.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('asset.posters.index_header'));
            $content->description(__('asset.posters.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Poster.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('asset.posters.create_header'));
            $content->description(__('asset.posters.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Poster in storage.
     *
     * @param PosterRequest $request
     *
     * @return Response
     */
    public function store(PosterRequest $request)
    {
        $input = $request->all();

        $poster = $this->posterRepository->create($input);

        Flash::success(__('asset.posters.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('asset.posters.index'));

    }

    /**
     * Display the specified Poster.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $poster = $this->posterRepository->findWithoutFail($id);

        if (empty($poster)) {
            Flash::error(__('asset.posters.not_found'));

            return redirect(route('asset.posters.index'));
        }

        return view('asset.posters.show')->with('poster', $poster);

    }

    /**
     * Show the form for editing the specified Poster.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('asset.posters.edit_header'));
            $content->description(__('asset.posters.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Poster in storage.
     *
     * @param  int              $id
     * @param PosterRequest $request
     *
     * @return Response
     */
    public function update($id, PosterRequest $request)
    {
        $poster = $this->posterRepository->findWithoutFail($id);

        if (empty($poster)) {
            Flash::error(__('asset.posters.not_found'));

            return redirect(route('asset.posters.index'));
        }
        $input = $request->all();

        $poster = $this->posterRepository->update($input, $id);

        Flash::success(__('asset.posters.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('asset.posters.index'));
    }

    /**
     * Remove the specified Poster from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->posterRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('asset.posters.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $poster = $this->posterRepository->findWithoutFail($id);

        if (empty($poster)) {
            Flash::error(__('asset.posters.not_found'));

            return redirect(route('asset.posters.index'));
        }

        if ($flag = $this->posterRepository->delete($id)) {

            return response()->json(['message' => __('asset.posters.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Poster::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->select('domain', '所属行业')->options(array(
                'ott'      => '媒体',
                'shopping' => '电商',
                'action'   => '活动',
                'crm'      => '营销',
            ));
            $sps = Sp::pluck('title', 'id');
            $form->select('spId', '服务商')->options($sps);
            $form->text('dataType', '数据类型');
            $form->text('metaType', '元数据类型');
            $form->text('metaId', '元数据ID');
            $form->text('posterId', '主海报Id');
            $form->text('thumbnail', '缩略图');
            $form->text('tags', '图片标签');
            $form->text('title', '图片标题');
            $form->text('subtitle', '图片副标题');
            $form->textarea('short_desc', '图片简介');
            $form->text('detail', '详情');
            $form->text('working', '工作态');
            $form->select('status', '审核态')->options(array(
                'to_check_online'          => '上线审核中',
                'to_apply_online_publish'  => '等待上线发布',
                'to_apply_offline'         => '等待下线申请',
                'to_check_offline'         => '下线审核中',
                'to_apply_offline_publish' => '等待下线发布',
            ))->default('to_check_online');
            $form->datetime('expire_at', '失效时间');
            $form->number('listorder', '排序字段');

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Poster::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('asset.posters.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('asset.posters.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('asset.posters.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('asset.posters.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('asset.posters.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('asset.posters.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('asset.posters.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('asset.posters.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('asset.posters.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('asset.posters.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('domain', '所属行业')->sortable();
            $grid->column('sp.title', '服务商')->sortable();
            $grid->column('dataType', '数据类型')->sortable();
            $grid->column('metaType', '元数据类型')->sortable();
            $grid->column('metaId', '元数据ID')->sortable();
            $grid->column('posterId', '主海报Id')->sortable();
            $grid->column('thumbnail', '缩略图')->sortable();
            $grid->column('tags', '图片标签')->sortable();
            $grid->column('title', '图片标题')->sortable();
            $grid->column('subtitle', '图片副标题')->sortable();
            $grid->column('short_desc', '图片简介')->sortable();
            $grid->column('detail', '详情')->sortable();
            $grid->column('working', '工作态')->sortable();
            $grid->column('status', '审核态')->sortable();
            $grid->column('expire_at', '失效时间')->sortable();
            $grid->column('listorder', '排序字段')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();

            });
        });
    }
}
